Subject: Re: counting 1 bits
From: [email-masked] (Steven A. Reisman)
Date: Tue, 14 Dec 1993 04:29:00 GMT
Newsgroups: comp.sys.amiga.programmer

Stefaan Decorte ([email-masked]) wrote:

: Does there exist an (efficient) instruction to count the number of 1 bits in a 
: unsigned long data type?  (preferably in C but assembler is also ok).
: Or does there exist a way around performing the inefficient 32-part loop?

Try the following:

#include <stdio.h>

int	cardcount(unsigned long x)
{
	x = (x & 0x55555555) + ((x >> 1) & 0x55555555);
	x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
	x = (x & 0x0F0F0F0F) + ((x >> 4) & 0x0F0F0F0F);
	return x % 255;
}

main ()
{
  printf("%d\n", cardcount(0xFFFFFFFF));
  printf("%d\n", cardcount(0x12345678));
  printf("%d\n", cardcount(0x12481248));
}
-- 
Steven A. Reisman
12695 4th St. S.                                  [email-masked]      
Afton, MN  55001                                      (612) 436-7125